<?php
namespace App\HttpController\Traits;

use EasySwoole\Http\Message\Status;
Trait Upload{

    protected function upload_file_common($extensions){
        $post=$this->request()->getParsedBody();
        if($post){
            $class=$this->request()->getRequestParam('class');
            $i=$this->request()->getRequestParam('i');
            $callback=$this->request()->getRequestParam('callback');
            $uniq=$this->request()->getRequestParam('uniq');
            //主要判断文件大小和类型
            $file=$this->request()->getUploadedFile('file');
            $error=$file->getError();
            if($error>0){
                $this->writeJson(Status::CODE_OK, ['code'=>$error,'msg'=>'fail','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
                return;
            }
            $size=$file->getSize();
            if($size>2*1024*1024){
                $this->writeJson(Status::CODE_OK, ['code'=>101,'msg'=>'文件超出最大大小','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
                return;
            }
            $filename=$file->getClientFilename();
            $ext=pathinfo($filename,PATHINFO_EXTENSION);
            
            if(!in_array($ext,$extensions)){
                $this->writeJson(Status::CODE_OK, ['code'=>102,'msg'=>'文件类型不正确','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
                return;
            }
            mt_srand();
            $destination=EASYSWOOLE_ROOT.'/public/uploads/'.date('Y/m/d').'/'.date('YmdHis').rand(100000,999999).'.'.$ext;
            if(!file_exists(dirname($destination))){
                mkdir(dirname($destination),0777,true);
            }
            $url=str_replace(EASYSWOOLE_ROOT.'/public','',$destination);
            $r=$file->moveTo($destination);
            if(!$r){
                $this->writeJson(Status::CODE_OK, ['code'=>103,'msg'=>'文件写入失败','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
                return;
            }
            //save to db
            if(method_exists($this,'save_attachment')){
                $this->save_attachment(0,$uniq,$url);
            }
            $this->writeJson(Status::CODE_OK, ['code'=>0,'msg'=>'success','url'=>$url,'class'=>$class,'i'=>$i,'callback'=>$callback], '');
            return;
        }
    }
    public function upload_img(){
        $get=$this->request()->getQueryParams();
        extract($get);
        //$class $i $callback;
        //$class='demo';
        //$i=0;
        //$callback='cb_thumb';
        if(!isset($class) or !isset($i) or !isset($callback) or !isset($uniq)){
            $this->msg(0,'lose class/i/callback/uniq');
        }
        $this->fetch('../Upload/img',get_defined_vars());
    }
    public function upload_img_action(){
        $extensions=[
            'jpg',
            'png',
            'gif',
        ];
        $this->upload_file_common($extensions);
    }
    public function upload_file(){
        $get=$this->request()->getQueryParams();
        extract($get);
        //$class $i $callback;
        //$class='demo';
        //$i=0;
        //$callback='cb_thumb';
        if(!isset($class) or !isset($i) or !isset($callback) or !isset($uniq)){
            $this->msg(0,'lose class/i/callback/uniq');
        }
        $this->fetch('../Upload/file',get_defined_vars());
    }
    public function upload_file_action(){
        $extensions=[
            'jpg',
            'png',
            'gif',
            'rar',
            'zip',
            'pdf',
            'txt',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'xls',
            'xlsx',
            'swf',
        ];
        $this->upload_file_common($extensions);
    }

    private function mkhtml($fn,$fileurl,$message)
	{
		$str='<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$fn.', \''.$fileurl.'\', \''.$message.'\');</script>';
		$this->response()->write($str);
    }
    
    protected function ck_common($extensions){
        $post=$this->request()->getParsedBody();
        if(!$post){
            $this->response()->write('only post');
        }
        $get=$this->request()->getRequestParam();
        extract($get);
        if(empty($CKEditorFuncNum)){
            $this->msg(0,'错误的功能调用请求！');
            return;
        }
        if(!isset($uniq)){
            $this->mkhtml(1,'','lose uniq!');
            return;
        }

        //主要判断文件大小和类型
        $file=$this->request()->getUploadedFile('upload');
        $error=$file->getError();
        if($error>0){
            $this->mkhtml($CKEditorFuncNum,'','error:'.$error);
            return;
        }
        $size=$file->getSize();
        if($size>2*1024*1024){
            $this->mkhtml($CKEditorFuncNum,'','文件超出最大大小');
            return;
        }
        $filename=$file->getClientFilename();
        $ext=pathinfo($filename,PATHINFO_EXTENSION);
        if(!in_array($ext,$extensions)){
            $this->mkhtml($CKEditorFuncNum,'','文件类型不正确');
            return;
        }
        mt_srand();
        $destination=EASYSWOOLE_ROOT.'/public/uploads/'.date('Y/m/d').'/'.date('YmdHis').rand(100000,999999).'.'.$ext;
        if(!file_exists(dirname($destination))){
            mkdir(dirname($destination),0777,true);
        }
        $url=str_replace(EASYSWOOLE_ROOT.'/public','',$destination);
        $r=$file->moveTo($destination);
        if(!$r){
            $this->mkhtml($CKEditorFuncNum,'','文件写入失败');
            return;
        }
        //save to db
        if(method_exists($this,'save_attachment')){
            $this->save_attachment(0,$uniq,$url);
        }
        $this->mkhtml($CKEditorFuncNum,$url,'上传成功！');
        return;
    }

    public function upload_ck_img(){
        $extensions=[
            'jpg',
            'png',
            'gif',
        ];
        $this->ck_common($extensions);
    }

    public function upload_ck_file(){
        $extensions=[
            'jpg',
            'png',
            'gif',
            'rar',
            'zip',
            'pdf',
            'txt',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'xls',
            'xlsx',
            'swf',
        ];
        $this->ck_common($extensions);
    }

    public function upload_huge(){
        $get=$this->request()->getQueryParams();
        extract($get);
        
        if(!isset($class) or !isset($i) or !isset($callback) or !isset($uniq)){
            $this->msg(0,'lose class/i/callback/uniq');
        }
        $this->fetch('../Upload/huge',get_defined_vars());
    }

    public function upload_huge_action(){
        //https://www.easyswoole.com/HttpServer/uploadFile.html
        //[2019-12-10 15:13:53 #3175.0]	WARNING	swPort_onRead_http: Content-Length is too big, MaxSize=[2096591]
        /*
data: (binary)
name: MX-19_x64.iso
total: 713
index: 1
fileSize: 1495269376
        */
        $request=  $this->request();
        $data = $request->getUploadedFile('data')->getStream();
        $name=$request->getRequestParam('name');
        $total=$request->getRequestParam('total');
        $index=$request->getRequestParam('index');
        $fileSize=$request->getRequestParam('fileSize');

        $class=$this->request()->getRequestParam('class');
        $i=$this->request()->getRequestParam('i');
        $callback=$this->request()->getRequestParam('callback');
        $uniq=$this->request()->getRequestParam('uniq');

        //主要判断文件大小和类型
        if($fileSize>2*1024*1024*1024){
            $this->writeJson(Status::CODE_OK, ['code'=>101,'msg'=>'文件超出最大大小','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
            return;
        }
        $ext=pathinfo($name,PATHINFO_EXTENSION);
        $extensions=[
            'jpg',
            'png',
            'gif',
            'rar',
            'zip',
            'pdf',
            'txt',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'xls',
            'xlsx',
            'swf',
			'iso',
        ];
        if(!in_array($ext,$extensions)){
            $this->writeJson(Status::CODE_OK, ['code'=>102,'msg'=>'文件类型不正确','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
            return;
        }
        $DEST=$this->session()->get('UPLOAD_HUGE_DEST');
        if($DEST){
            $destination=$DEST;
        }else{
            mt_srand();
            $destination=EASYSWOOLE_ROOT.'/public/uploads/'.date('Y/m/d').'/'.date('YmdHis').rand(100000,999999).'.'.$ext;    
            $this->session()->set('UPLOAD_HUGE_DEST',$destination);
        }
        
        if(!file_exists(dirname($destination))){
            mkdir(dirname($destination),0777,true);
        }
        $url=str_replace(EASYSWOOLE_ROOT.'/public','',$destination);

        //如果第一次上传的时候，该文件已经存在，则删除文件重新上传
        if($index==1 && file_exists($destination) && filesize($destination)==$fileSize){
            unlink($destination);
        }
        //合并文件
        $r=file_put_contents($destination, $data, FILE_APPEND);
        if(!$r){
            $this->writeJson(Status::CODE_OK, ['code'=>103,'msg'=>'文件写入失败','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
            return;
        }
        //最后一块时
        if($index==$total){
            //save to db
            if(method_exists($this,'save_attachment')){
                $this->save_attachment(0,$uniq,$url);
            }
            $this->session()->unset('UPLOAD_HUGE_DEST');
            $this->writeJson(Status::CODE_OK, ['code'=>0,'msg'=>'success','url'=>$url,'class'=>$class,'i'=>$i,'callback'=>$callback], '');
            return;
        }
        //继续上传
        $this->writeJson(Status::CODE_OK, ['code'=>0,'msg'=>'success','url'=>'','class'=>$class,'i'=>$i,'callback'=>$callback], '');
        return;
    }
    public function upload_img_tradition(){
        $get=$this->request()->getQueryParams();
        extract($get);
        //$class $i $callback;
        //$class='demo';
        //$i=0;
        //$callback='cb_thumb';
        if(!isset($class) or !isset($i) or !isset($callback) or !isset($uniq)){
            $this->msg(0,'lose class/i/callback/uniq');
        }
        $this->fetch('../Upload/img_tradition',get_defined_vars());
    }
    public function upload_img_tradition_action(){
        $extensions=[
            'jpg',
            'png',
            'gif',
        ];
        $this->upload_file_common($extensions);
    }
    public function upload_file_tradition(){
        $get=$this->request()->getQueryParams();
        extract($get);
        //$class $i $callback;
        //$class='demo';
        //$i=0;
        //$callback='cb_thumb';
        if(!isset($class) or !isset($i) or !isset($callback) or !isset($uniq)){
            $this->msg(0,'lose class/i/callback/uniq');
        }
        $this->fetch('../Upload/file_tradition',get_defined_vars());
    }
    public function upload_file_tradition_action(){
        $extensions=[
            'jpg',
            'png',
            'gif',
            'rar',
            'zip',
            'pdf',
            'txt',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'xls',
            'xlsx',
            'swf',
        ];
        $this->upload_file_common($extensions);
    }



}